"""
A Taskbar Icon
"""

import os
import sys
import wx

from Base.menu import Menu
from BitTornado.__init__ import  product_name
from LMG.Utility.constants import *

NOTIFY_SUPPORT = 0
if os.name == 'nt':
    try:
        import win32gui
        NOTIFY_SUPPORT = 1
    except:
        pass        
elif sys.platform == "darwin":
    try:
        import Growl
        NOTIFY_SUPPORT = 2
    except:
        pass
        
        

class TaskBarIcon(wx.TaskBarIcon):
    """
    Task Bar Icon Class
    """
    
    def __init__(self, parent):
        wx.TaskBarIcon.__init__(self)
        self.close = False
        
        self.icon = utility.smallIcon
        self.SetRestoreFromTaskbar()

        # Initialize messages
        self._messages = {"Download Task Completed": _("Download Task Completed!"),
                          "Seeding Task Completed": _("Seeding Task Completed!")}

        if NOTIFY_SUPPORT == 2:
            icon = Growl.Image.imageFromPath(os.path.join(utility.path, 'icon_bt.ico'))
            self._growl = Growl.GrowlNotifier(product_name, self._messages.keys(), applicationIcon = icon)
            self._growl.register() 

        self.updateIcon()
        
    def SetRestoreFromTaskbar(self):
        if utility.config.Read('mintray_singleclick', "boolean"): 
            self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, None)
            self.Bind(wx.EVT_TASKBAR_LEFT_UP, utility.frame.onTaskBarActivate)
        else:
            self.Bind(wx.EVT_TASKBAR_LEFT_UP, None)
            self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, utility.frame.onTaskBarActivate)

        if wx.Platform != "__WXMAC__":
            self.TBMENU_RESTORE = wx.NewId()
            self.Bind(wx.EVT_MENU, utility.frame.onTaskBarActivate, id = self.TBMENU_RESTORE)
            
        
        
    def ShowBalloonTip(self, title, msg):
        """
        Show Balloon tooltip
         @param title: The title of the balloon
         @param msg: The tooltip message itself
        """
        # Is notification disabled ?
        if not utility.config.Read('mintray_balloontips', "boolean"):
            return

            
        # NT Balloon notification
        if NOTIFY_SUPPORT == 1:
            if utility.frame.IsIconized() and self.IsIconInstalled():
                try:
                    self.SetBalloonTip(self.icon.GetHandle(), title, msg)
                except Exception, e:
                   print e
                
        # Growl notification
        elif NOTIFY_SUPPORT == 2:
            try:
                self.SetGrowlTip(title, msg)
            except Exception, e:
                print e
                
        # No notification
        else:
            utility.config.Write('mintray_balloontips', False, "boolean")
    
    def SetGrowlTip(self, title, msg):
        self._growl.notify(title, self._messages[title], msg)

    def SetBalloonTip(self, hicon, title, msg):
        lpdata = (self.GetIconHandle(),
                  99,
                  win32gui.NIF_MESSAGE | win32gui.NIF_ICON | win32gui.NIF_INFO,
                  0,
                  hicon,
                  '', msg, 0, self._messages[title], win32gui.NIIF_INFO)
        win32gui.Shell_NotifyIcon(win32gui.NIM_MODIFY, lpdata)

    def GetIconHandle(self):
        if not hasattr(self, "_chwnd"):
            try:
                for handle in wx.GetTopLevelWindows():
                    handle = handle.GetHandle()
                    if len(win32gui.GetWindowText(handle)) == 0 and \
                       win32gui.GetWindowRect(handle) == (0,0,400,250):
                        self._chwnd = handle
                        break
                if not hasattr(self, "_chwnd"):
                    raise Exception
            except:
                raise Exception, "Icon window not found"
        return self._chwnd
    
    def updateIcon(self, iconifying = False, close = False):
        """
        Updates icon (show/hide)
        """
        if self.close:
            return
        if close:
            self.close = True
        remove = True
        
        mintray = utility.config.Read('mintray', "int")
        if (mintray >= 3) or ((mintray >= 1) and iconifying):
            remove = False
        
        if remove and self.IsIconInstalled():
            self.RemoveIcon()
        elif not remove and not self.IsIconInstalled():
            self.setIcon()

    def setIcon(self, text = product_name):
        self.SetIcon(self.icon, text)
        
    def CreatePopupMenu(self):
        """
        Shows right-click popup menu for the icon
        """
        menu = Menu('taskbarmenu')
        if wx.Platform != "__WXMAC__":
            menu.Prepend(self.TBMENU_RESTORE, _('Toggle window'))        
        return menu
